import { getCurrentUserId } from '@/utils/backend/auth'
import { prisma } from '@/utils/backend/db'
import { HttpStatus } from '@/utils/httpStatus'
import { NextResponse } from 'next/server'

// 创建聊天室
export async function POST(req: Request) {
	try {
		const token = req.headers.get('Authorization')?.replace('Bearer ', '')!

		const { friendId } = await req.json()
		const currentUserId = await getCurrentUserId(token)

		// 查找或创建私聊会话
		const chat = await prisma.chat.upsert({
			where: {
				user1Id_user2Id: {
					user1Id: Math.min(currentUserId, friendId),
					user2Id: Math.max(currentUserId, friendId),
				},
			},
			create: {
				type: 'private',
				user1Id: Math.min(currentUserId, friendId),
				user2Id: Math.max(currentUserId, friendId),
			},
			update: {},
		})

		return NextResponse.json({
			success: true,
			data: chat,
		})
	} catch (error) {
		console.error('Create chat failed:', error)
		return NextResponse.json(
			{
				success: false,
				message: '创建聊天失败',
			},
			{ status: HttpStatus.INTERNAL_SERVER_ERROR }
		)
	}
}

// 获取聊天室列表
export async function GET(req: Request) {
	try {
		const token = req.headers.get('Authorization')?.replace('Bearer ', '')!
		const currentUserId = await getCurrentUserId(token)
		// 获取当前用户信息
		const currentUser = await prisma.user.findUnique({
			where: { id: currentUserId },
		})

		if (!currentUser) {
			return NextResponse.json(
				{
					success: false,
					message: '用户不存在',
				},
				{ status: HttpStatus.NOT_FOUND }
			)
		}

		// 查找用户参与的所有聊天
		const chats = await prisma.privateChat.findMany({
			where: {
				OR: [{ user1Id: currentUserId }, { user2Id: currentUserId }],
			},
			include: {
				user1: true,
				user2: true,
				messages: {
					where: {
						// 只获取对方发送的消息
						NOT: {
							senderId: currentUserId,
						},
					},
					orderBy: {
						createdAt: 'desc',
					},
					take: 1,
					include: {
						sender: true,
					},
				},
			},
		})

		// 处理返回数据格式
		const chatList = await Promise.all(
			chats.map(async (chat) => {
				const contact = chat.user1Id === currentUserId ? chat.user2 : chat.user1

				// 获取未读消息数
				const unreadCount = await prisma.privateMessage.count({
					where: {
						chatId: chat.id,
						senderId: contact.id, // 对方发送的消息
						status: 'sent', // 未读状态
						createdAt: {
							// 用户最后登出时间之后的消息
							gt: new Date(currentUser.lastLogoutAt || new Date(0)),
						},
					},
				})

				return {
					id: chat.id,
					contact,
					lastMessage: chat.messages[0]?.content || null, // 只会是对方的最后一条消息
					unreadCount,
					updatedAt: chat.updatedAt,
				}
			})
		)

		return NextResponse.json({
			success: true,
			data: chatList,
		})
	} catch (error) {
		console.error('Get chat list failed:', error)
		return NextResponse.json(
			{
				success: false,
				message: '获取聊天列表失败',
			},
			{ status: HttpStatus.INTERNAL_SERVER_ERROR }
		)
	}
}
